import flask, flask.views
import os
import functools
from flask import Flask
from werkzeug.serving import run_simple
from modelos.usuario import Usuario
from modelos.validar import validar, getUsuarios
app = flask.Flask(__name__)
# Don't do this!
app.secret_key = "bacon"

#users = {'jake':'bacon'}
#comentario

class Main(flask.views.MethodView):
    def get(self):
        return flask.render_template('index.html')
    
    def post(self):
        if 'logout' in flask.request.form:
            flask.session.pop('username', None)
            return flask.redirect(flask.url_for('index'))
        required = ['username', 'passwd']
        for r in required:
            if r not in flask.request.form:
                flask.flash("Error: {0} is required.".format(r))
                return flask.redirect(flask.url_for('index'))
        username = flask.request.form['username']
        passwd = flask.request.form['passwd']
        #if username in users and users[username] == passwd:
        if validar(username, passwd):
            flask.session['username'] = username
           # usuarios = getUsuarios
            #print "Holaa"
            #print usuarios
            
            
        else:
            flask.flash("Username doesn't exist or incorrect password")
        return flask.redirect(flask.url_for('menu'))

def login_required(method):
    @functools.wraps(method)
    def wrapper(*args, **kwargs):
        if 'username' in flask.session:
            return method(*args, **kwargs)
        else:
            flask.flash("A login is required to see the page!")
            return flask.redirect(flask.url_for('index'))
    return wrapper

class Remote(flask.views.MethodView):
    @login_required
    def get(self):
        return flask.render_template('remote.html')
        
    @login_required
    def post(self):
        result = eval(flask.request.form['expression'])
        flask.flash(result)
        return flask.redirect(flask.url_for('remote'))
    
class Menu(flask.views.MethodView):
    @login_required
    def get(self):
        return flask.render_template('menu.html')
    @login_required
    def post(self):
        return flask.render_template('menu.html')
    
app.add_url_rule('/',
                 view_func=Main.as_view('index'),
                 methods=["GET", "POST"])
app.add_url_rule('/remote/',
                 view_func=Remote.as_view('remote'),
                 methods=['GET', 'POST'])
app.add_url_rule('/menu/',
                 view_func=Menu.as_view('menu'),
                 methods=["GET", "POST"])

app.debug = True
run_simple("localhost", 4503, app, use_reloader=True, use_debugger=True, use_evalex=True)